using HCore.Core;
using HCore.IOC.Beans.Factory.Attribute.Attr;
using HCore.IOC.Context.Event.Attr;
using HCore.IOC.Context.Stereotype;
using HCore.Tests.Runtime.ShootingEditor2D.Scripts.Support.CommandQuery;
using HCore.Tests.Runtime.ShootingEditor2D.Scripts.System.GunSystem;
using HCore.Unity.Core;

namespace HCore.Tests.Runtime.ShootingEditor2D.Scripts.Command
{
    /// <summary>
    ///     装弹命令
    /// </summary>
    public class ReloadCommand : Singleton<ReloadCommand>, ICommand
    {
    }

    [Component]
    public class ReloadCommandHandler
    {
        [Autowired] private IGunSystem mGunSystem;

        [EventListener]
        public void ExecuteCommand(ReloadCommand command)
        {
            // 当前的枪
            var currentGun = mGunSystem.CurrentGun;
            // 当前枪的配置
            var currentGunConfigItem = mGunSystem.CurrentGunConfigItem;

            // 不是闲置的，跳过
            if (currentGun.GunState.Value != GunState.Idle
                // 弹夹满的，跳过
                || currentGun.BulletCountInGun.Value == currentGunConfigItem.BulletMaxCount
                // 没有后备子弹，跳过    
                || currentGun.BulletCountOutGun.Value <= 0) return;

            // 需要装弹的数量
            var needBulletCount = currentGunConfigItem.BulletMaxCount - currentGun.BulletCountInGun.Value;

            // 不需要装弹
            if (needBulletCount <= 0) return;

            // 切换状态
            currentGun.GunState.Value = GunState.Reload;

            // 装弹是需要时间的，装弹完成后，恢复闲置状态
            FunctionTimer.Create(() =>
            {
                // 后备子弹多余需要的装弹量
                if (currentGun.BulletCountOutGun.Value >= needBulletCount)
                {
                    currentGun.BulletCountInGun.Value += needBulletCount;
                    currentGun.BulletCountOutGun.Value -= needBulletCount;
                }
                // 后备子弹不够了，但是也尽可能装弹
                else
                {
                    currentGun.BulletCountInGun.Value += currentGun.BulletCountOutGun.Value;
                    currentGun.BulletCountOutGun.Value = 0;
                }

                // 变更回闲置状态
                currentGun.GunState.Value = GunState.Idle;
            }, currentGunConfigItem.ReloadSeconds);
        }
    }
}